package com.zpark.servlet_filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * @PackageName: com.zpark.servlet_filter
 * @ClassName: ServletFilterDemo02
 * @Description:
 * @author: RZS
 * @date: 2023/3/13  15:02
 */
//@WebFilter("/user/login.do")
//@WebFilter("*.do")
@WebFilter("/user/*")
public class ServletFilterDemo02 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        /**
         * 判断请求头当中是否包含token
         * 如果不包含token则拦截请求，不让访问，重定向到/sd01.do
         * 否则放行访问后续资源
         */
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取请求头token信息
        String token = request.getHeader("token");
        if (token == null) {
            // 不包含token则拦截请求，不让访问，重定向到/sd01.do
            response.sendRedirect(request.getContextPath() + "/sd01.do");
        } else {
            // 放行访问后续资源
            filterChain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {

    }
}
